from datetime import datetime

from flask import render_template, request, jsonify, session, redirect, url_for, g
from sqlalchemy import extract

from models import db
from models.index import User, News, Category
from . import admin_blu


@admin_blu.route("/")
def admin():
    # user_id = session.get("user_id")
    # user = db.session.query(User).filter(User.id == user_id).first()
    if not g.user:
        # 如果用户未登录，那么直接跳转到前台首页
        return redirect(url_for("index.index"))

    return render_template("admin/index.html", user=g.user)


@admin_blu.route("/user_count.html")
def user_count():
    # 查询总数
    total_count = db.session.query(User).count()

    # 统计当月用户的新增数量
    now_date = datetime.now()  # datetime
    year = now_date.year
    month = now_date.month
    month_count = db.session.query(User).filter(
        extract("year", User.create_time) == year, extract("month", User.create_time) == month).count()

    # 统计当天用户的新增数量
    day = now_date.day
    day_count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                              extract('month', User.create_time) == month,
                                              extract('day', User.create_time) == day).count()

    return render_template("admin/user_count.html", total_count=total_count, month_count=month_count,
                           day_count=day_count)


@admin_blu.route("/user_list.html")
def user_list():
    page = request.args.get("page", 1)
    paginate = db.session.query(User).paginate(page=int(page), per_page=5, error_out=False)
    return render_template("admin/user_list.html", paginate=paginate)


@admin_blu.route("/news_review.html")
def news_review():
    page = request.args.get("page", 1)
    paginate = db.session.query(News).order_by(-News.create_time).paginate(int(page), 5, False)
    return render_template("admin/news_review.html", paginate=paginate)


@admin_blu.route("/news_review_detail.html")
def news_review_detail():
    new_id = request.args.get("id")
    new = db.session.query(News).filter(News.id == new_id).first()
    return render_template("admin/news_review_detail.html", new=new)


@admin_blu.route("/news_review_detail/<int:new_id>", methods=["POST"])
def save_news_review_detail(new_id):
    # 获取新闻
    new = db.session.query(News).filter(News.id == new_id).first()
    if not new:
        # 如果没有这个新闻就返回error信息
        return jsonify({
            "errno": 5003,
            "errmsg": "未找到对应新闻"
        })
    # 提取审核结果
    action = request.json.get("action")
    if action == "accept":
        new.status = 0
    else:
        new.status = -1
    db.session.commit()
    return jsonify({
        "errno": 0,
        "errmsg": "成功"
    })


@admin_blu.route("/news_edit.html")
def news_edit():
    page = request.args.get("page", 1)
    paginate = db.session.query(News).paginate(page=int(page), per_page=5, error_out=False)
    return render_template("admin/news_edit.html", paginate=paginate)


@admin_blu.route("/news_edit_detail.html")
def news_edit_detail():
    new_id = request.args.get("id")
    new = db.session.query(News).filter(News.id == new_id).first()
    categories = db.session.query(Category).filter(Category.id != 0).all()
    return render_template("admin/news_edit_detail.html", new=new, categories=categories)


@admin_blu.route("/news_edit_detail/<int:new_id>", methods=["POST"])
def save_news_edit_detail(new_id):
    new = db.session.query(News).filter(News.id == new_id).first()
    if not new:
        return jsonify({
            "errno": 5001,
            "errmsg": "未找到该新闻"
        })
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    new.title = title
    new.category_id = category_id
    new.digest = digest
    new.content = content
    db.session.commit()
    return jsonify({
        "errno": 0,
        "errmsg": "修改成功"
    })


@admin_blu.route("/news_type.html")
def news_type():
    page = request.args.get("page", 1)
    paginate = db.session.query(Category).filter(Category.id != 1).paginate(page=int(page), per_page=5,
                                                                            error_out=False)
    return render_template("admin/news_type.html", paginate=paginate)


@admin_blu.route("/news_type", methods=["POST"])
def news_type_edit():
    cid = request.json.get("id")
    cname = request.json.get("name")
    if not cid:
        if cname in [category.id for category in db.session.query(Category).all()]:
            ret = {
                "errno": 5001,
                "errmsg": "该类已经存在"
            }
            return jsonify(ret)
        category = Category(name=cname)
        try:
            db.session.add(category)
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "成功"
            }

            return jsonify(ret)
        except:
            ret = {
                "errno": 5002,
                "errmsg": "添加失败"
            }
            return jsonify(ret)
    else:
        category = db.session.query(Category).filter(Category.id == int(cid) + 1).first()
        if category:
            category.name = cname
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "成功"
            }
            return jsonify(ret)
        ret = {
            "errno": 5002,
            "errmsg": "修改失败"
        }
        return jsonify(ret)
